550A - Two Substrings - CodeForces Solution


brute force dp greedy implementation strings *1500

Please click on ads to support us..

Python Code:

import sys,os,math,cmath,timeit,functools,operator,bisect
from sys import stdin,stdout,setrecursionlimit
from io import BytesIO, IOBase
from collections import defaultdict as dd , Counter
from math import factorial , gcd
from queue import PriorityQueue
from heapq import merge, heapify, heappop, heappush
try :
    from functools import cache , lru_cache
    from sortedcontainers import *
except :
    pass 

ONLINE_JUDGE = __debug__

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        import os
        self.os = os
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
        self.BUFSIZE = 8192

    def read(self):
        while True:
            a = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
            if not a:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(a), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            a = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
            self.newlines = a.count(b"\n") + (not a)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(a), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            self.os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


stdin, stdout = IOWrapper(stdin), IOWrapper(stdout)

input = lambda: stdin.readline().rstrip("\r\n")

start = timeit.default_timer()

primes = []
mod=10**9+7
MOD=998244353


def seive(n):
    a = []
    prime = [True for i in range(n+1)] 
    p = 2
    while (p * p <= n): 
        if (prime[p] == True): 
            for i in range(p ** 2,n + 1, p): 
                prime[i] = False
        p = p + 1
    for p in range(2,n + 1): 
        if prime[p]: 
            primes.append(p)

def lower_bound(arr, n, k):
    start = 0
    end = n-1
    while start <= end:
        mid = (start+end)//2
        if arr[mid] == k:
            return mid
        elif arr[mid] > k:
            if mid > 0:
                if arr[mid-1] < k:
                    return (mid-1)
            else:
                return -1
        else:
            if mid < (n-1):
                if arr[mid+1] > k:
                    return mid
            else:
                return mid

def upper_bound(arr, n, k):
    start = 0
    end = n-1
    while start <= end:
        mid = (start+end)//2
        if arr[mid] == k:
            return mid
        elif arr[mid] > k:
            if mid > 0:
                if arr[mid-1] < k:
                    return (mid)
            else:
                return mid
        else:
            if mid < (n-1):
                if arr[mid+1] > k:
                    return (mid+1)
            else:
                return -1

def is_sorted(arr):
    return all(arr[i]<=arr[i+1] for i in range(len(arr)-1))

def invmod(n):
    return pow(n,mod-2,mod)

def binary_search(a,x,lo=0,hi=None):
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        midval = a[mid]
        if midval < x:
            lo = mid+1
        elif midval > x: 
            hi = mid
        else:
            return mid
    return -1

def ceil(a:int,b:int)->int :
    return (a+b-1)//b

def yn(x):
    if x :
        print("YES")
    else :
        print("NO")

def nCr(n,r):
    return factorial(n)//(factorial(r)*factorial(n-r))


def solve():
    s=strin()
    if len(s) <= 3 :
        yn(0)
        return
    mp = [[],[]]
    for i,c in enumerate(s) :
        if i+1<len(s) and s[i]=='A' and s[i+1]=='B' :
            mp[0].append(i)
        if i+1<len(s) and s[i]=='B' and s[i+1]=='A' :
            mp[1].append(i)
    mp[0].sort() ; mp[1].sort()
    if not mp[0] or not mp[1] :
        yn(0)
        return
        for x in mp[0] :
        if bisect.bisect_right(mp[1],x+1)!=len(mp[1]):
            yn(1)
            return
    for x in mp[1] :
        if bisect.bisect_right(mp[0],x+1)!=len(mp[0]):
            yn(1)
            return
    yn(0)

def main():
    tc=1
        for _ in range(tc):
        solve()
    stop = timeit.default_timer()
    if not ONLINE_JUDGE :
        print("Time Elapsed :" , str(stop-start) , "seconds")


def lst()->list :
    return list(map(int,input().split()))

def rowinp() :
    return map(int,input().split())

def strin()->str :
    return input()

def chlst()->list :
    return [x for x in input()]

def sint()->int :
    return int(input())


main()

C++ Code:

#include <iostream>
#include <algorithm>

using namespace std;

string s;

bool check(const string& a, const string& b) {
    bool a_happened = false;
    string ans;
    for(int i = 0; i < s.length() - 1; i++) {
        string temp;
        temp += s[i];
        temp += s[i + 1];
        if(temp == a && !a_happened) {
            a_happened = true;
            i++;
        } else if(temp == b && a_happened) {
            return true;
        }
    }
    return false;
}

int main() {
    cin >> s;
    cout << (check("AB", "BA") || check("BA", "AB") ? "YES\n" : "NO\n");
}


Comments

Submit
1 Comments
  • 2/2/2024 19:48 - Africa/Cairo

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s;
    cin >> s;
    int found1 = s.find("AB");
    int found2 = s.find("BA");
    if (found1 != -1 && found2 != -1 && (found2 - found1) != 1)
    {
        cout << "YES";
    }
    else
        cout << "NO";
    return 0;
}


More Questions

905. Sort Array By Parity
1351. Count Negative Numbers in a Sorted Matrix
617. Merge Two Binary Trees
1450. Number of Students Doing Homework at a Given Time
700. Search in a Binary Search Tree
590. N-ary Tree Postorder Traversal
589. N-ary Tree Preorder Traversal
1299. Replace Elements with Greatest Element on Right Side
1768. Merge Strings Alternately
561. Array Partition I
1374. Generate a String With Characters That Have Odd Counts
1822. Sign of the Product of an Array
1464. Maximum Product of Two Elements in an Array
1323. Maximum 69 Number
832. Flipping an Image
1295. Find Numbers with Even Number of Digits
1704. Determine if String Halves Are Alike
1732. Find the Highest Altitude
709. To Lower Case
1688. Count of Matches in Tournament
1684. Count the Number of Consistent Strings
1588. Sum of All Odd Length Subarrays
1662. Check If Two String Arrays are Equivalent
1832. Check if the Sentence Is Pangram
1678. Goal Parser Interpretation
1389. Create Target Array in the Given Order
1313. Decompress Run-Length Encoded List
1281. Subtract the Product and Sum of Digits of an Integer
1342. Number of Steps to Reduce a Number to Zero
1528. Shuffle String